<template>
  <div class="page-layout">
    <div class="area">
      <el-card class="item flex-gap">
        <div class="title">
          <span>各班当月产量</span>
        </div>
        <div class="progress">
          <el-progress v-for="(percentage, key) in progress" :key="key" type="dashboard" :percentage="percentage" @click="progressClick(key)">
            <span>{{ key }}班：{{ percentage }}%</span>
          </el-progress>
        </div>
      </el-card>
      <el-card class="item flex-gap">
        <div class="progress-container">
          <div
            v-for="(segment, index) in segments"
            :key="index"
            class="progress-segment"
            :style="{
              width: `${segment.percent * 100}%`,
              backgroundColor: segment.color,
            }"
          >
            <span>{{ segment.name }}: {{ segment.time }}分钟</span>
          </div>
        </div>
        <el-table
          :data="shutdownData"
          max-height="20vh"
          :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          show-overflow-tooltip
          size="small"
        >
          <el-table-column prop="accidentName" label="时间段" />
          <el-table-column prop="date" label="时间" />
          <el-table-column prop="responsibleParty" label="责任方" />
          <el-table-column prop="handlingOpinion" label="处理意见" />
        </el-table>
      </el-card>
    </div>
    <div class="area">
      <el-card class="item h-40vh">
        <div class="radio-single">
          <el-radio-group v-model="radio" text-color="#626aef" fill="rgb(239, 240, 253)" size="small">
            <el-radio-button label="日" value="day" />
            <el-radio-button label="月" value="month" />
          </el-radio-group>
        </div>
        <graph-bar-line
          :data-bar1="[1420, 1420, 1420, 1420, 1420, 1420, 1420, 1420]"
          :data-bar2="[1508, 1427, 1339, 1687, 1543, 1439, 1322, 1763]"
          :data-line1="[106.2, 100.49, 94.3, 118.8, 108.66, 101.34, 93.1, 124.15]"
          :data-line2="[122.3, 115.73, 108.6, 136.82, 125.14, 116.71, 107.22, 142.98]"
          :datax="['2025-09-01', '2025-09-02', '2025-09-03', '2025-09-04', '2025-09-05', '2025-09-06', '2025-09-07', '2025-09-08']"
          :title="title"
          :bar-name="['计划产量', '实际产量']"
          :line-name="['完成率', '产能利用率']"
          :format-val="['完成率', '产能利用率']"
        />
      </el-card>
      <el-card class="item h-40vh">
        <graph-bar-line
          :data-bar1="[3200, 2210, 3600, 4010]"
          :data-bar2="[2876, 2211, 3601, 4011]"
          :data-bar3="[6689, 2212, 3602, 4012]"
          :data-bar4="[3800, 2213, 3603, 4013]"
          :datax="['外板', '1.0厚度以下', '1.0-1.5厚度', '1.5以上厚度']"
          :title="'品规生产分布'"
          :bar-name="['甲', '乙', '丙', '丁']"
          style="margin-top: 24px"
        />
      </el-card>
    </div>
    <div class="area">
      <el-card class="item">
        <graph-bar-line
          :data-bar1="[6912, 6912, 6912, 6912, 6912, 6912, 6912, 6912]"
          :data-bar2="[7845, 7541, 5484, 7845, 6948, 7840, 7544, 7201]"
          :data-line1="[113, 109, 79, 113, 101, 113, 109, 114]"
          :datax="['2025-05-31', '2025-06-01', '2025-06-02', '2025-06-03', '2025-06-04', '2025-06-05', '2025-06-06', '2025-06-07']"
          :title="'5#镀锌月产能利用率'"
          :bar-name="['计划产量', '实际产量']"
          :line-name="['产能利用率']"
          :format-val="['产能利用率']"
        />
      </el-card>
      <el-card class="item">
        <el-table
          :data="prodData"
          :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          show-overflow-tooltip
          size="small"
          max-height="25vh"
          ><!-- 班组列 -->
          <el-table-column prop="crew" label="班组" />
          <!-- 月计划生产时长列 -->
          <el-table-column prop="monthPlanHours" label="月计划生产时长" />
          <!-- 实际生产时长列 -->
          <el-table-column prop="actualHours" label="实际生产时长" />
          <!-- 检修时长列 -->
          <el-table-column prop="maintenanceHours" label="检修时长" />
          <!-- 停机累计列 -->
          <el-table-column prop="stopHours" label="停机累计" />
          <!-- 影响产量列 -->
          <el-table-column prop="impactOutput" label="影响产量" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, onUnmounted, nextTick, defineComponent, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import GraphBarLine from './components/GraphBarLine.vue';
  import dayjs from 'dayjs';

  const progress = reactive({ A: 95, B: 90, C: 80, D: 65 });

  interface Segment {
    name: string;
    time: number;
    color: string;
    percent: number; // 计算后的宽度占比（0~1）
  }

  interface TableRow {
    crew: string;
    monthPlanHours: string; // 可根据实际业务改为 number 类型
    actualHours: string;
    maintenanceHours: string;
    stopHours: string;
    impactOutput: string;
  }

  const minPercent = 0.15; // 最低占比
  const segments = ref<Segment[]>([
    { name: '生产', time: 14, color: '#f37021', percent: 0 },
    { name: '设备', time: 66, color: '#4cae4c', percent: 0 },
    { name: '其他', time: 20, color: '#999', percent: 0 },
  ]);
  const shutdownData = ref([
    { accidentName: '事故名称1', date: '2022-01-01 10:00:00', responsibleParty: '责任方1', handlingOpinion: '处理意见1' },
    { accidentName: '事故名称2', date: '2022-01-02 12:00:00', responsibleParty: '责任方2', handlingOpinion: '处理意见2' },
  ]);

  const radio = ref('day');
  const title = ref('A班产量展示');

  const prodData = ref<TableRow[]>([
    { crew: '甲', monthPlanHours: '', actualHours: '', maintenanceHours: '', stopHours: '', impactOutput: '' },
    { crew: '乙', monthPlanHours: '', actualHours: '', maintenanceHours: '', stopHours: '', impactOutput: '' },
    { crew: '丙', monthPlanHours: '', actualHours: '', maintenanceHours: '', stopHours: '', impactOutput: '' },
    { crew: '丁', monthPlanHours: '', actualHours: '', maintenanceHours: '', stopHours: '', impactOutput: '' },
  ]);

  const progressClick = (process: string) => {
    if (!progress.hasOwnProperty(process)) {
      ElMessage.error(`未找到${process}班`);
      return;
    }
    // ElMessage.success(`点击了${process}班`);
    title.value = `${process}班产量展示`;
  };

  // 计算各分段占比
  const calcPercentages = () => {
    const totalTime = segments.value.reduce((sum, s) => sum + s.time, 0);

    // 处理总时间为 0 的边界情况（平均分配）
    if (totalTime === 0) {
      segments.value.forEach((s) => {
        s.percent = 1 / segments.value.length;
      });
      return;
    }

    const basePercents = segments.value.map((s) => s.time / totalTime); // 基础占比（无最低限制时的占比）
    const lowIndexList = basePercents.map((p, i) => (p < minPercent ? i : -1)).filter((i) => i !== -1); // 记录需要强制最低占比的分段索引
    const lowCount = lowIndexList.length;
    const minTotal = lowCount * minPercent; // 最低占比的总和
    let remaining = 1 - minTotal; // 剩余可分配的占比

    // 防止最低占比总和超过 1（极端情况，若出现则平均分配）
    if (remaining < 0) {
      segments.value.forEach((s) => {
        s.percent = 1 / segments.value.length;
      });
      return;
    }

    // 对“非最低占比分段”分配剩余占比
    const validBasePercents = basePercents.map((p, i) => (lowIndexList.includes(i) ? 0 : p));
    const validTotal = validBasePercents.reduce((a, b) => a + b, 0);

    segments.value.forEach((s, i) => {
      if (lowIndexList.includes(i)) {
        s.percent = minPercent;
      } else {
        s.percent = (basePercents[i] / validTotal) * remaining;
      }
    });
  };

  onMounted(() => {
    calcPercentages();
  });

  onUnmounted(() => {
    console.log('组件卸载');
  });
</script>
<style lang="less" scoped>
  .page-layout {
    width: 99%;
    position: relative;
    background-color: #fff;
    min-height: 100vh;
    margin-bottom: 1vh;
  }

  .area {
    display: flex;
    flex-wrap: nowrap;
    gap: 1vw;
    padding: 5px;

    .item {
      height: 30vh;
      width: 50%;
    }

    .h-40vh {
      height: 40vh;
    }
  }

  .flex-gap {
    :deep(.el-card__body) {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
  }

  .radio-single {
    display: flex;
    justify-content: flex-end;
    z-index: 2;
  }

  .title {
    font-size: 1.4rem;
    font-weight: 700;
    text-align: center;
    min-height: 6vh;
  }

  .progress {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1vw;

    :deep(.el-progress) {
      display: flex;
      justify-content: center;
    }
  }

  .progress-container {
    display: flex;
    flex-wrap: nowrap;
    min-height: 4vh;
    color: #fff;
  }

  .progress-segment {
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
